package com.bjsxt.service.impl;

import com.bjsxt.pojo.Book;
import com.bjsxt.service.BookService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class BookServiceImpl implements BookService {
    @Override
    public List<Book> findAll() {
        List<Book> list=null;
        SqlSession sqlSession=null;
        try {
            InputStream input = Resources.getResourceAsStream("mybatis.xml");
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(input);
             sqlSession = factory.openSession();
             list = sqlSession.selectList("a.book.selectAll");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            sqlSession.close();
        }

        return list;
    }

    @Override
    public int save(Book book) {

        SqlSession sqlSession=null;
        int insert=0;
        try {
            InputStream input = Resources.getResourceAsStream("mybatis.xml");
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(input);
            sqlSession = factory.openSession();
             insert= sqlSession.insert("a.book.insert", book);

             sqlSession.commit();
        } catch (IOException e) {
            e.printStackTrace();
            sqlSession.rollback();
        }finally {
            sqlSession.close();
        }
        return insert;
    }
}
